package com.cskaoyan.controller;

import com.cskaoyan.bean.BaseParam;
import com.cskaoyan.bean.Coupon;
import com.cskaoyan.bean.OrderInfoVO;
import com.cskaoyan.bean.basebean.BaseRespVo;
import com.cskaoyan.bean.wx_search.OrderMsg;
import com.cskaoyan.bean.zhao_order_bean.*;
import com.cskaoyan.mapper.CouponMapper;
//import com.cskaoyan.rocket.Produce;
import com.cskaoyan.service.CommentService;
import com.cskaoyan.service.CouponService;
import com.cskaoyan.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;

/**
 * <h3>market</h3>
 *
 * @author:Zhao
 * @date:2021-10-21 10:26:33
 * @description:小程序订单业务
 */
@RestController
@RequestMapping("wx/order")
public class WxOrderController {
    @Autowired
    OrderService orderService;

    @Autowired
    CommentService commentService;

    @Autowired
    CouponService couponService;

    //@Autowired
    //private Produce produce;

    @RequestMapping("list")
    public BaseRespVo list(Short showType, BaseParam baseParam) {
        BasePageData data = orderService.wxQuery(showType, baseParam);

        return BaseRespVo.ok(data);
    }


    //用户取消订单，order表中order_status状态码改为102（用户取消）
    @RequestMapping("cancel")
    public BaseRespVo cancel(@RequestBody Map map) {
        String orderId = String.valueOf(map.get("orderId")) ;
        int orderId2 = Integer.parseInt(orderId);

        orderService.cancel(orderId2);

        return BaseRespVo.ok();
    }

    //查看订单详情
    @RequestMapping("detail")
    public BaseRespVo detail(Integer orderId) {

        OrderInfoVO orderInfoVO = orderService.wxDetail(orderId);

        return BaseRespVo.ok(orderInfoVO);
    }

    //删除订单
    @RequestMapping("delete")
    public BaseRespVo delete(@RequestBody Map map) {
        String orderId = String.valueOf(map.get("orderId")) ;
        int orderId2 = Integer.parseInt(orderId);

        orderService.delete(orderId2);

        return BaseRespVo.ok();
    }

    //评价订单 将数据插入 market_comment TODO 待测试，重点是图片路径映射
    //请求参数（json）：
    //content: "评价"
    //hasPicture: false
    //orderGoodsId: 13
    //picUrls: []
    //star: 5
    @RequestMapping("comment")
    public BaseRespVo comment(@RequestBody CommentBO commentBO) {


        int commentStatus = commentService.insertComment(commentBO);

        if (commentStatus == 200) {
            return BaseRespVo.ok();
        }

        return BaseRespVo.fail("评论没有成功发送");
    }


    //用户选择退款
    @RequestMapping("refund")
    public BaseRespVo refund(@RequestBody Map map) {
        Integer orderId = (Integer) map.get("orderId");

        orderService.wxRefund(orderId);

        return BaseRespVo.ok();
    }

    //用户确认订单
    @RequestMapping("confirm")
    public BaseRespVo confirm(@RequestBody Map map) {
        Integer orderId = (Integer) map.get("orderId");

        orderService.confirm(orderId);

        return BaseRespVo.ok();
    }

    @RequestMapping("goods")
    public BaseRespVo goods(Integer orderId,Integer goodsId){
        OrderGoods orderGoods = orderService.selectInfoGood(orderId,goodsId);
        if (orderGoods== null)
            return BaseRespVo.fail();


        return BaseRespVo.ok(orderGoods);
    }


    //在购物车中提交订单
    //addressId: 10      //地址id，根据地址表查找，填入订单
    //cartId: 0         // 购物车id，暂不知何意（获取数量、规格？）
    //couponId: 0       //优惠券id，根据优惠券表查找，将优惠金额放入订单
    //grouponLinkId: 0
    //grouponRulesId: 0
    //message: ""        //提交订单时可填写留言，直接放入订单中
    //userCouponId:         团购，本项目无需做
    //提交订单时就删掉优惠券
    @RequestMapping("submit")
    public BaseRespVo submit(@RequestBody SubmitBO submitBO) {
        int orderId = orderService.submit(submitBO);
//        SubmitVO submitVO =
        if (orderId == -1) {
            return BaseRespVo.fail("库存不足");
        }
        if (orderId == 0) {
            return BaseRespVo.fail("创建订单异常");
        }

        //删除优惠券
        couponService.deleteCouponById(submitBO.getCouponId());

     /*   //得到订单编号:
        DateTimeFormatter df_year = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
        LocalDateTime date = LocalDateTime.now();
        String datestr = date.format(df_year);

        //消息,指定用户id和订单编号
        OrderMsg msg = new OrderMsg();
        msg.setUserId(userId);
        msg.setOrderSn(userId+"_"+datestr);

        String msgJson = JSON.toJSONString(msg);
        //生成一个信息，标签在这里手动指定
        Message message = new Message(RocketConstants.TOPIC, "carttag", msgJson.getBytes());
        //delaytime的值:
        //messageDelayLevel=1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h
        message.setDelayTimeLevel(5);
        //发送信息
        SendResult sendResult = producer.getProducer().send(message);
        System.out.println("时间:"+ TimeUtil.getTimeNow()+";生产者发送一条信息，内容:{"+msgJson+"},结果:{"+sendResult+"}");*/
        return BaseRespVo.ok(new SubmitVO(orderId));
    }

    //付款（直接把订单状态改为已付款）
    //orderId: "28"
    //orderId: 31
    @RequestMapping("prepay")
    public BaseRespVo prepay(@RequestBody Map map) {
        Object id = map.get("orderId");

        if (id instanceof Integer) {
            Integer orderId = (Integer) id;
            orderService.prepay(orderId);
        }else if (id instanceof String) {
            String orderId = (String) id;
            orderService.prepay(Integer.parseInt(orderId));
        }

        return BaseRespVo.ok("订单不能支付");
        //return BaseRespVo.fail("订单不能支付");
    }



}
